class PageTranslator {
    constructor() {
        this.translationBar = null;
        this.isTranslating = false;
        this.cache = new Map();
        this.currentTargetLanguage = 'zh'; // 默认翻译为中文
    }

    // 初始化翻译功能
    init() {
        this.createTranslationBar();
        this.setupEventListeners();
    }

    // 创建翻译控制栏
    createTranslationBar() {
        this.translationBar = document.createElement('div');
        this.translationBar.className = 'translation-bar';
        this.translationBar.innerHTML = `
            <div class="translation-controls">
                <button id="translate-toggle">翻译页面</button>
                <select id="target-language">
                    <option value="zh">中文</option>
                    <option value="en">English</option>
                    <option value="ja">日本語</option>
                </select>
                <div class="progress-bar" style="display: none;">
                    <div class="progress"></div>
                </div>
            </div>
        `;
        document.body.insertBefore(this.translationBar, document.body.firstChild);
    }

    // 设置事件监听
    setupEventListeners() {
        const translateButton = this.translationBar.querySelector('#translate-toggle');
        translateButton.addEventListener('click', () => this.toggleTranslation());

        const languageSelect = this.translationBar.querySelector('#target-language');
        languageSelect.addEventListener('change', (e) => {
            this.currentTargetLanguage = e.target.value;
            if (this.isTranslating) {
                this.translatePage();
            }
        });
    }

    // 切换翻译状态
    async toggleTranslation() {
        if (this.isTranslating) {
            this.restoreOriginal();
        } else {
            await this.translatePage();
        }
        this.isTranslating = !this.isTranslating;
    }

    // 翻译整个页面
    async translatePage() {
        try {
            const textNodes = this.getTranslatableNodes(document.body);
            const progressBar = this.translationBar.querySelector('.progress-bar');
            const progress = progressBar.querySelector('.progress');
            const translateButton = this.translationBar.querySelector('#translate-toggle');
            
            // 更新UI状态
            progressBar.style.display = 'block';
            progressBar.classList.add('show');
            translateButton.disabled = true;
            translateButton.textContent = '翻译中...';
            
            let completed = 0;
            const total = textNodes.length;

            // 批量处理翻译，每次处理5个节点
            const batchSize = 5;
            for (let i = 0; i < total; i += batchSize) {
                const batch = textNodes.slice(i, i + batchSize);
                await Promise.all(batch.map(async (node) => {
                    if (this.shouldTranslateNode(node)) {
                        const originalText = node.textContent.trim();
                        if (originalText) {
                            if (!this.cache.has(originalText)) {
                                const translatedText = await this.translateText(originalText);
                                if (translatedText && translatedText !== originalText) {
                                    this.cache.set(originalText, translatedText);
                                    node.textContent = translatedText;
                                }
                            } else {
                                node.textContent = this.cache.get(originalText);
                            }
                        }
                    }
                    completed++;
                    progress.style.width = `${(completed / total) * 100}%`;
                }));

                // 给API一个短暂的休息时间
                await new Promise(resolve => setTimeout(resolve, 100));
            }

            // 等待一小段时间后隐藏进度条（让用户能看到翻译完成）
            await new Promise(resolve => setTimeout(resolve, 500));

            // 恢复UI状态
            progressBar.classList.remove('show');
            setTimeout(() => {
                progressBar.style.display = 'none';
            }, 300);
            
            translateButton.disabled = false;
            translateButton.textContent = '显示原文';
            this.isTranslating = true;
        } catch (error) {
            console.error('Page translation error:', error);
            // 恢复UI状态
            const progressBar = this.translationBar.querySelector('.progress-bar');
            const translateButton = this.translationBar.querySelector('#translate-toggle');
            progressBar.classList.remove('show');
            setTimeout(() => {
                progressBar.style.display = 'none';
            }, 300);
            translateButton.disabled = false;
            translateButton.textContent = '翻译页面';
            this.isTranslating = false;
            
            // 显示错误消息
            alert('翻译过程中出现错误，请稍后重试');
        }
    }

    // 获取可翻译的文本节点
    getTranslatableNodes(element) {
        const walker = document.createTreeWalker(
            element,
            NodeFilter.SHOW_TEXT,
            {
                acceptNode: function(node) {
                    return NodeFilter.FILTER_ACCEPT;
                }
            }
        );

        const textNodes = [];
        let node;
        while (node = walker.nextNode()) {
            textNodes.push(node);
        }
        return textNodes;
    }

    // 判断节点是否需要翻译
    shouldTranslateNode(node) {
        const parent = node.parentElement;
        if (!parent) return false;

        // 跳过脚本和样式标签
        const skipTags = ['SCRIPT', 'STYLE', 'CODE', 'PRE'];
        if (skipTags.includes(parent.tagName)) return false;

        // 跳过空文本或只包含空白字符的文本
        if (!node.textContent.trim()) return false;

        return true;
    }

    // 调用翻译API
    async translateText(text) {
        try {
            // 使用 LibreTranslate API
            const response = await fetch('https://libretranslate.de/translate', {
                method: 'POST',
                body: JSON.stringify({
                    q: text,
                    source: 'auto',
                    target: this.currentTargetLanguage,
                    format: 'text'
                }),
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json'
                }
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => null);
                throw new Error(errorData?.error || `HTTP error! status: ${response.status}`);
            }

            const data = await response.json();
            return data.translatedText;
        } catch (error) {
            console.error('Translation API error:', error.message);
            // 返回原文，避免显示undefined
            return text;
        }
    }

    // 恢复原始文本
    restoreOriginal() {
        const textNodes = this.getTranslatableNodes(document.body);
        textNodes.forEach(node => {
            const translatedText = node.textContent.trim();
            for (const [original, translated] of this.cache.entries()) {
                if (translated === translatedText) {
                    node.textContent = original;
                    break;
                }
            }
        });
    }
}

// 初始化翻译器
const translator = new PageTranslator();
translator.init();
